<?php

namespace app\msgapi\service;

use app\msgapi\model\{AdminUser, AuthGroup, AuthRule, System, User};
use app\utils\{Arr, Str};
use think\facade\Cache;

class IndexService extends BaseService
{
    private AdminUser $adminUser;
    private System $system;
    public function __construct(AdminUser $adminUser, System $system)
    {
        parent::__construct();
        $this->adminUser = $adminUser;
        $this->system = $system;
    }

    // 修改密码
    public function updatePassword($adminid)
    {
        $data = input('post.');
        if($check = $this->adminUser->validate($data,'up')){
            return error_json($check);
        }
        $res = $this->adminUser->where(['id'=>$adminid])->value('password');  // 当前密码
        if(!password_verify(md5($data['old_password']),$res)){
            return error_json('原密码不正确');
        }
        try{
            $this->adminUser::update(['password'=>$data['password'],'last_pass'=>time()],['id'=>$adminid]);
            return ajax_return(0,'修改成功,请重新登录');
        }catch (\Exception $e){
            return error_json('修改失败,请重试');
        }
    }

    public function updateEmail(array $data, $adminid)
    {
        if (!isset($data['email'])) {
            $email = $this->adminUser->where([['id','=',$adminid]])->value('email');
            return success_json('成功',['email'=>$email]);
        }
        if ($check = $this->adminUser->validate($data, 'upemail')) {
            return error_json($check);
        }
        try {
            $this->adminUser::update(['email'=>$data['email']], ['id'=>$adminid]);
            return ajax_return(0, '修改成功');
        }catch (\Exception $e) {
            return error_json('修改失败,请重试');
        }
    }

    // 清缓存
    public function clearCache()
    {
        if(Cache::clear()){
            return success_json('清除成功');
        }else{
            return error_json('清除失败，请检查缓存权限');
        }
    }

    /**配置信息
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSystemAll()
    {
        return success_json('成功',$this->system->select()->column('val','name'));
    }

    /**更新配置信息
     * @return \think\response\Json
     */
    public function updateConfig()
    {
        $config_type = input('post.config_type');
        $data['val'] =  input($config_type.'/a');
        try{
            if($this->system->where(['name'=>$config_type])->count() > 0){
                $this->system::update($data,['name'=>$config_type]);
            }else{
                $data['name'] = $config_type;
                $this->system::create($data);
            }
            Cache::set('conf_'.$config_type, $data['val']);// 保存或更新时同步更新缓存
            HsoperateLogService::addLog(2, request()->adminid,"修改了[平台/回调]{$config_type}配置",json_encode($data,256));
            return success_json('保存成功');
        }catch (\Exception $e){
            return error_json('保存失败，请重试');
        }
    }

    /**获取菜单
     * @param string $admin_groupid
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getMenu(string $admin_groupid)
    {
        $authRuleList = AuthRule::where([['type','=',1],['state','=',1]])->order(['sort' => 'DESC', 'id' => 'ASC'])->select()->toArray();
        $authGroup = new AuthGroup();
        $rules = $authGroup->getRulesShow($admin_groupid);// 获取当前用户组授权的所有id（包含父级id）

        // 超级管理员有所有的权限，非超级管理员根据授权id
        if($admin_groupid != 1){
            foreach ($authRuleList as $key=>$value) {
                if (!in_array($value['id'], $rules)) {  // 菜单的id不在权限中去除
                    unset($authRuleList[$key]);
                }
            }
        }
        return success_json('成功',Arr::arrayToTree($authRuleList));
    }

    //获取客户与聊天统计信息
    public function get_base_data($data)
    {
            $cust_data = HuihuaCustService::getBaseData($data);
            $msg_data = HuihuaMsgService::getBaseData($data);
            return success_json('成功',compact('cust_data','msg_data'));

    }
    //获取客户与聊天统计折线图信息
    public function get_echats_data($data)
    {
            $cust_data = HuihuaCustService::getEchatsData($data);
            $msg_data = HuihuaMsgService::getEchatsData($data);
            $date = [];
            $custdata = [];
            $msgdata=[];
            foreach ($cust_data as $key=>$val){
                $date[] = $val['add_time'];
                $custdata[] = $val['count'];
                $msgdata[] = $msg_data[$key]['count'];
            }
            return success_json('成功',compact('date','custdata','msgdata'));

    }

    /**获取登入用户信息
     * @param $adminid
     * @return \think\response\Json
     */
    public function getUserInfo($adminid)
    {
        $admin = AdminUser::where('id','=',$adminid)->findOrEmpty()->toArray();
        if($admin['userid']){
            $userinfo = User::where('userid','=',$admin['userid'])->findOrEmpty()->toArray();
            return success_json('成功',$userinfo);
        }
        return error_json('暂无信息');
    }
    /**获取js签名信息
     * @param $data
     * @return \think\response\Json
     * @throws \Throwable
     */
    public function getJsTicketInfo($data)
    {
        $corpInfo = HscorpInfoService::getCorpInfo(env('wework.corpid'),true); //获取企业密钥信息
        $corpId =  $corpInfo['corp_info']['corpid'];
        $agentid = $corpInfo['corp_info']['agent_id'];
        $weweorkcorpself = new WeworkCorpSelfService();
        $jsapiticket = $weweorkcorpself->getJsApiTicket();
        $agnetJsapiTicket = $weweorkcorpself->getAgentJsApiTicket();
        $url = urldecode($data['url']);
        $noncestr = Str::createNonceStr(8);
        $timestamp = time();
        $signature = "jsapi_ticket={$jsapiticket}&noncestr={$noncestr}&timestamp={$timestamp}&url={$url}";
        $agentSignature = "jsapi_ticket={$agnetJsapiTicket}&noncestr={$noncestr}&timestamp={$timestamp}&url={$url}";
        $signature = sha1($signature);
        $agnetJsapiTicket = sha1($agentSignature);
        $data = [
            'corpid' => $corpId,
            'agentid' => $agentid,
            'noncestr' => $noncestr,
            'timestamp' => $timestamp,
            'url' => $url,
            'signature' => $signature,
            'agnetJsapiTicket' => $agnetJsapiTicket
        ];
        return success_json('获取成功', $data);
    }
}